<template>
  <!--  多图片上传   -->
  <el-upload
      v-if="props.isMultiple"
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleDelete"
      :on-success="handleSuccess"
      :show-file-list="true"
      action="#"
      list-type="picture-card"
  >
    <el-icon>
      <Plus/>
    </el-icon>
  </el-upload>

  <!--  单图片上传   -->
  <el-upload
      v-else
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-success="handleSuccess"
      :show-file-list="true"
      action="#"
      class="upload-delete"
      list-type="picture-card"
  >
    <el-icon>
      <Plus/>
    </el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img
        :src="dialogImageUrl"
        alt="Preview Image"
        class="dialog-image"
        w-full
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, watchEffect} from "vue";
import {Plus} from "@element-plus/icons-vue";
import {UploadFile} from "element-plus";
import {getTencentToken} from "@/api/tencent";
import {md5} from "js-md5";
import COS from 'cos-js-sdk-v5'

const props = defineProps(["isMultiple", "isUpload", "uploadList", "pathPrefix"]);

const emit = defineEmits(["uploadFile", "deleteFile"]);

const fileList = ref([]);
const fileData = ref({});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const uploadListHandleStatus = ref(false);

const isUpload = ref(false);

// 回调函数
const uploadFile = (uploadFile) => {
  emit("uploadFile", uploadFile);
};

// 回调函数
const deleteFile = (deleteFile) => {
  emit("deleteFile", deleteFile);
};

// 删除
const handleDelete = (file) => {
  deleteFile(file);
};

// 上传图片
const beforeUpload = async (file) => {
  // 获取当前日期做目录
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const dateDir = `/${currentYear}/${currentMonth}/${currentDay}`
  // 获取随机数
  const number = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000

  const pathPrefix = props.pathPrefix + dateDir

  // 名称md5加密
  const [prefixName, suffix] = file.name.split('.')
  const name = md5(prefixName) + '.' + suffix

  // 在上传之前设置文件名
  const filename = pathPrefix + `/${Date.now()}_${number}_${name}`

  const tokenData = await getTencentToken({pathPrefix: props.pathPrefix})
  console.log(tokenData)

  const cos = new COS({
    getAuthorization: function (options, callback) {
      callback({
        TmpSecretId: tokenData.data.tmpSecretId,
        TmpSecretKey: tokenData.data.tmpSecretKey,
        SecurityToken: tokenData.data.token,
        ExpiredTime: tokenData.data.expiredTime,
        StartTime: tokenData.data.startTime,
      })
    },
  })

  const params = {
    Bucket: tokenData.data.bucket,
    Region: tokenData.data.region,
    Key: filename,
    Body: file, // 这是一个 File 对象，通常来自 <input type="file">
  }

  try {
    const response = await cos.putObject(params)
    if (response.statusCode === 200) {

      // 上传完成的处理
      fileData.value = {
        name: filename,
        url: tokenData.data.domain + '/' + filename,
      }

      console.log("tokenData.data.domain:", tokenData.data.domain)
      console.log("filename:", filename)
      console.log(fileData.value)

      // 判断是否为多文件上传
      if (props.isMultiple === true) {
        fileList.value.push(fileData.value);
      } else {
        fileList.value[0] = fileData.value;
      }

      // 上传成功，将文件传回父组件
      await uploadFile(fileList.value)
    }
  } catch (error) {
    console.error('上传失败:', error)
  }
  return false
}


// 上传成功后处理
const handleSuccess = () => {
};

// 放大查看
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const init = function () {
  console.log(props.uploadList)
  props.uploadList.forEach((item) => {
    fileList.value.push(item)
  })
}

watchEffect(() => {
  init()
})

</script>

<style>
/**
  控制是否显示删除按钮
 */

.upload-delete span.el-upload-list__item-delete {
  display: none !important;
}

.dialog-image {
  width: 100%;
}
</style>
